﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSP.Common.IProviders;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Web;
using System.Configuration;
using CSP.Common.Tools;
using CSP.Common.Factories;

namespace CSP.Common.Providers
{
    public class TencentWeiBoApiProvider : OtherApiProvider
    {
        public override string AccessToken
        {
            get
            {
                if (HttpContext.Current.Session["OtherAccessToken"] != null)
                {
                    return HttpContext.Current.Session["OtherAccessToken"].ToString();
                }
                return "";
            }
            set
            {
                HttpContext.Current.Session["OtherAccessToken"] = value;
            }
        }

        /// <summary>
        /// 腾讯微博Uid
        /// </summary>
        public string TencentWeiBoUid
        {
            get
            {
                return ConfigurationManager.AppSettings["TencentWeiBoUid"];
            }
        }

        /// <summary>
        /// 腾讯AppKey
        /// </summary>
        public string TencentWeiBoAppKey
        {
            get
            {
                return ConfigurationManager.AppSettings["TencentWeiBoAppKey"];
            }
        }

        /// <summary>
        /// 腾讯AppSecret
        /// </summary>
        public string TencentWeiBoAppSecret
        {
            get
            {
                return ConfigurationManager.AppSettings["TencentWeiBoAppSecret"];
            }
        }


        /// <summary>
        /// 腾讯微博登陆跳转授权
        /// </summary>
        public string TencentWeiBoAuthorizeUri
        {
            get
            {
                return ConfigurationManager.AppSettings["TencentWeiBoAuthorize"];
            }
        }

        /// <summary>
        /// 腾讯微博获取获取授权Uri
        /// </summary>
        public string TencentWeiBoAccessTokenUri
        {
            get
            {
                return ConfigurationManager.AppSettings["TencentWeiBoAccessToken"];
            }
        }

        ///// <summary>
        ///// 腾讯微博授权查询
        ///// </summary>
        //public string TencentWeiBoGetTokenInfoUri
        //{
        //    get
        //    {
        //        return ConfigurationManager.AppSettings["TencentWeiBoGetTokenInfo"];
        //    }
        //}

        /// <summary>
        /// 营销标题
        /// </summary>
        private string MarketingMsg
        {
            get
            {
                return ConfigurationManager.AppSettings["MarketingMsg"];
            }
        }

        /// <summary>
        /// 营销描述
        /// </summary>
        private string MarketingDescription
        {
            get
            {
                return ConfigurationManager.AppSettings["MarketingDescription"];
            }
        }

        /// <summary>
        /// 发布腾讯微博
        /// </summary>
        public string TencentWeiBoPublishInfoUri
        {
            get
            {
                return ConfigurationManager.AppSettings["TencentWeiBoPublishInfo"];
            }
        }

        /// <summary>
        /// 关注腾讯微博
        /// </summary>
        public string TencentWeiBoAttentionUri
        {
            get
            {
                return ConfigurationManager.AppSettings["TencentWeiBoAttention"];
            }
        }

        /// <summary>
        /// 获取腾讯微博用户信息
        /// </summary>
        public string TencentWeiBoUserInfoUri
        {
            get
            {
                return ConfigurationManager.AppSettings["TencentWeiBoUserInfo"];
            }
        }

        /// <summary>
        /// 用户Id
        /// </summary>
        public override string Uid
        {
            get
            {

                if (HttpContext.Current.Session["otherUid"] != null)
                {
                    return HttpContext.Current.Session["otherUid"].ToString();
                }
                else
                {
                    return "";
                }

            }
            protected set
            {
                HttpContext.Current.Session["otherUid"] = value;
            }
        }

        /// <summary>
        /// 请求API登陆授权
        /// </summary>
        /// <returns></returns>
        public override void RequestApiAuthorization(string backUrl)
        {

            string requestUrl = TencentWeiBoAuthorizeUri + "?client_id=" + TencentWeiBoAppKey + "&response_type=code&redirect_uri=" + HttpContext.Current.Server.UrlEncode(backUrl);
            HttpContext.Current.Response.Redirect(requestUrl);
        }

        /// <summary>
        /// 根据请求的Code值，和重定向的Uri获取用户基本信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="redirectUri"></param>
        /// <param name="openId">openId可为空</param>
        /// <returns></returns>
        public override Dictionary<string, string> GetUserInfo(string code, string redirectUri,string openId="")
        {
            if(!string.IsNullOrWhiteSpace(openId))
            {
                Uid = openId;
            }
            GetAccessToken(code, redirectUri);
            Dictionary<string, string> result = GetUserInfoByAccessToken(AccessToken, Uid);
            return result;
        }

        /// <summary>
        ///Api事件处理管道“关注/微博”
        /// </summary>
        /// <param name="isPublish"></param>
        /// <param name="isAttention"></param>
        public override void EventHandling(bool isPublish, bool isAttention)
        {
            if (isPublish)
            {
                PublishInfo();
            }

            if (isAttention)
            {
                Attention();
            }
        }

        /// <summary>
        /// 获取权限令牌AccessToken
        /// </summary>
        /// <param name="code">腾讯Code</param>
        /// <param name="redirectUri">回调的链接地址</param>
        /// <returns></returns>
        private Dictionary<string,string> GetAccessToken(string code, string redirectUri)
        {
            string redirecturl = "client_id=" + TencentWeiBoAppKey + "&client_secret=" + TencentWeiBoAppSecret + "&grant_type=authorization_code" +
                    "&code=" + code + "&redirect_uri=" + HttpContext.Current.Server.UrlEncode(redirectUri);
            string json = CommonTool.MakePostByUrlAndPostData(TencentWeiBoAccessTokenUri, redirecturl);
            Dictionary<string, string> accessToken = AnalysisTencentWeiBoAccessToken(json);
            string access_token = accessToken["access_token"];
            AccessToken = access_token;
            //Uid = accessToken["uid"];
            return accessToken;
        }

        /// <summary>
        /// 根据AccessToken获取用户信息
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        private Dictionary<string, string> GetUserInfoByAccessToken(string accessToken, string uid)
        {
            string getUserInfoUrl = TencentWeiBoUserInfoUri;
            string redirecturl = getUserInfoUrl + "?oauth_version=2.a&format=json&scope=all&access_token=" + accessToken + "&openid=" + uid + "&oauth_consumer_key=" + TencentWeiBoAppKey + "&clientip=" + CommonTool.GetIP();
            string json = CommonTool.MakeGetByUrl(redirecturl);
            Dictionary<string, string> status=AnalysisTencentWeiboResult(json);
            if (status["ret"] != "0")
            {
                ILoggerProvider logger = LoggerFactory.GetErrorLogger();
                logger.Warn("(警告)腾讯微博获取用户信息失败:" + json + "  [openId]:" + Uid + "[Token]:" + AccessToken); 
            }
            Dictionary<string, string> result = AnalysisTencentGetUserInfo(json);
            return result;
        }

        private void PublishInfo()
        {
            string request;
            string tencentWeiBoPublishInfo = TencentWeiBoPublishInfoUri;
            string marketing = HttpContext.Current.Server.UrlEncode(MarketingMsg+MarketingDescription);
            //request = tencentWeiBoPublishInfo + "?status=" + marketingMsg+"&access_token=" + accessToken ;
            request = "oauth_consumer_key=" + TencentWeiBoAppKey + "&oauth_version=2.a" + "&openid=" + Uid + "&scope=all" + "&access_token=" + AccessToken + "&format=json" + "&clientip=" + CommonTool.GetIP() + "&content=" + marketing;
            string json = CommonTool.MakePostByUrlAndPostData(tencentWeiBoPublishInfo, request);
            Dictionary<string, string> jsonDic = AnalysisTencentWeiboResult(json);
            if (jsonDic["ret"] != "0")
            {
                ILoggerProvider logger = LoggerFactory.GetErrorLogger();
                logger.Warn("(警告)腾讯微博关注:" + json + "  [openId]:" + Uid + "[Token]:" + AccessToken);
            }
        }

        private void Attention()
        {
            string request;
            //关注
            string tencentWeiBoAttention = TencentWeiBoAttentionUri;
            string uid = TencentWeiBoUid;
            request = "oauth_consumer_key=" + TencentWeiBoAppKey + "&oauth_version=2.a" + "&openid=" + Uid + "&scope=all" + "&access_token=" + AccessToken + "&format=json" + "&clientip=" + CommonTool.GetIP() + "&name=" + TencentWeiBoUid + "&access_token=" + AccessToken;
            string json = CommonTool.MakePostByUrlAndPostData(tencentWeiBoAttention, request);
            Dictionary<string, string> jsonDic = AnalysisTencentWeiboResult(json);
            if (jsonDic["ret"] != "0")
            {
                ILoggerProvider logger = LoggerFactory.GetErrorLogger();
                logger.Warn("(警告)腾讯微博关注:" + json + "  [openId]:" + Uid + "[Token]:" + AccessToken);
            }
        }


        /// <summary>
        /// 解析腾讯微博获取授权
        /// </summary>
        /// <param name="json"></param>
        private Dictionary<string, string> AnalysisTencentWeiBoAccessToken(string json)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            //JObject obj = (JObject)JsonConvert.DeserializeObject(json);
            string[] participle = json.Split('&');
            for (int i = 0; i < participle.Length;i++ )
            {
                string element=participle[i];
                dic.Add(element.Split('=')[0], element.Split('=')[1]);
            }
            //权限token
            //string access_token = obj["access_token"].ToString().Replace("\"", "");
            //string expires_in = obj["expires_in"].ToString().Replace("\"", "");
            //string remind_in = obj["remind_in"].ToString().Replace("\"", "");
            //dic.Add("access_token", access_token);
            //dic.Add("expires_in", expires_in);
            //dic.Add("remind_in", remind_in);

            return dic;
        }

        ///// <summary>
        ///// 解析腾讯微博查询授权信息
        ///// </summary>
        ///// <param name="json"></param>
        //private Dictionary<string, string> AnalysisSinaGetTokenInfo(string json)
        //{
        //    Dictionary<string, string> dic = new Dictionary<string, string>();
        //    JObject obj = (JObject)JsonConvert.DeserializeObject(json);
        //    //权限token
        //    string create_at = obj["create_at"].ToString().Replace("\"", "");
        //    string scope = obj["scope"].ToString().Replace("\"", "");
        //    string expires_in = obj["expires_in"].ToString().Replace("\"", "");
        //    string remind_in = obj["appkey"].ToString().Replace("\"", "");
        //    string uid = obj["uid"].ToString().Replace("\"", "");
        //    dic.Add("create_at", create_at);
        //    dic.Add("scope", scope);
        //    dic.Add("expires_in", expires_in);
        //    dic.Add("remind_in", remind_in);
        //    dic.Add("uid", uid);

        //    return dic;
        //}

        /// <summary>
        /// 解析腾讯微博的用户基本信息
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private Dictionary<string, string> AnalysisTencentGetUserInfo(string json)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            JObject obj = (JObject)JsonConvert.DeserializeObject(json);

            //errcode : 返回错误码,
            string errcode = obj["errcode"].ToString().Replace("\"", "");
            //msg : 错误信息,
            string msg = obj["msg"].ToString().Replace("\"", "");
            //ret : 返回值，0-成功，非0-失败,
            string ret = obj["ret"].ToString().Replace("\"", "");
            //fansnum : 听众数,
            string fansnum = obj["data"]["fansnum"].ToString().Replace("\"", "");
            //favnum : 收藏数,
            string favnum = obj["data"]["favnum"].ToString().Replace("\"", "");
            //head : 头像url,
            string head = obj["data"]["head"].ToString().Replace("\"", "")+"/100";
            //homecity_code : 家乡所在城市id,
            string homecity_code = obj["data"]["homecity_code"].ToString().Replace("\"", "");
            //homecountry_code : 家乡所在国家id,
            string homecountry_code = obj["data"]["homecountry_code"].ToString().Replace("\"", "");
            //homepage : 个人主页,
            string homepage = obj["data"]["homepage"].ToString().Replace("\"", "");
            //homeprovince_code : 家乡所在省id,
            string homeprovince_code = obj["data"]["homeprovince_code"].ToString().Replace("\"", "");
            //hometown_code : 家乡所在城镇id,
            string hometown_code = obj["data"]["hometown_code"].ToString().Replace("\"", "");
            //idolnum : 收听的人数,
            string idolnum = obj["data"]["idolnum"].ToString().Replace("\"", "");
            //industry_code : 行业id,
            string industry_code = obj["data"]["industry_code"].ToString().Replace("\"", "");
            //introduction : 个人介绍,
            string introduction = obj["data"]["introduction"].ToString().Replace("\"", "");
            //isent : 是否企业机构,
            string isent = obj["data"]["isent"].ToString().Replace("\"", "");
            //ismyblack : 是否在当前用户的黑名单中，0-不是，1-是,
            string ismyblack = obj["data"]["ismyblack"].ToString().Replace("\"", "");
            //ismyfans : 是否是当前用户的听众，0-不是，1-是,
            string ismyfans = obj["data"]["ismyfans"].ToString().Replace("\"", "");
            //ismyidol : 是否是当前用户的偶像，0-不是，1-是,
            string ismyidol = obj["data"]["ismyidol"].ToString().Replace("\"", "");
            //isrealname : 是否实名认证，1-已实名认证，2-未实名认证,
            string isrealname = obj["data"]["isrealname"].ToString().Replace("\"", "");
            //isvip : 是否认证用户，0-不是，1-是,
            string isvip = obj["data"]["isvip"].ToString().Replace("\"", "");
            //location : 所在地,
            string location = obj["data"]["location"].ToString().Replace("\"", "");
            //mutual_fans_num : 互听好友数,
            string mutual_fans_num = obj["data"]["mutual_fans_num"].ToString().Replace("\"", "");
            //name : 用户帐户名,
            string name = obj["data"]["name"].ToString().Replace("\"", "");
            //nick : 用户昵称,
            string nick = obj["data"]["nick"].ToString().Replace("\"", "");
            //openid : 用户唯一id，与name相对应,
            string openid = obj["data"]["openid"].ToString().Replace("\"", "");
            //province_code : 地区id,
            string province_code = obj["data"]["province_code"].ToString().Replace("\"", "");
            //regtime : 注册时间,
            string regtime = obj["data"]["regtime"].ToString().Replace("\"", "");
            //send_private_flag : 是否允许所有人给当前用户发私信，0-仅有偶像，1-名人+听众，2-所有人,
            string send_private_flag = obj["data"]["send_private_flag"].ToString().Replace("\"", "");
            //sex : 用户性别，1-男，2-女，0-未填写,
            string sex = obj["data"]["sex"].ToString().Replace("\"", "");


            //errcode : 返回错误码,
            dic.Add("errcode", errcode);
            //msg : 错误信息,
            dic.Add("msg", msg);
            //ret : 返回值，0-成功，非0-失败,
            dic.Add("ret", ret);
            //fansnum : 听众数,
            dic.Add("fansnum", fansnum);
            //favnum : 收藏数,
            dic.Add("favnum", favnum);
            //head : 头像url,
            dic.Add("head", head);
            //homecity_code : 家乡所在城市id,
            dic.Add("homecity_code", homecity_code);
            //homecountry_code : 家乡所在国家id,
            dic.Add("homecountry_code", homecountry_code);
            //homepage : 个人主页,
            dic.Add("homepage", homepage);
            //homeprovince_code : 家乡所在省id,
            dic.Add("homeprovince_code", homeprovince_code);
            //hometown_code : 家乡所在城镇id,
            dic.Add("hometown_code", hometown_code);
            //idolnum : 收听的人数,
            dic.Add("idolnum", idolnum);
            //industry_code : 行业id,
            dic.Add("industry_code", industry_code);
            //introduction : 个人介绍,
            dic.Add("introduction", introduction);
            //isent : 是否企业机构,
            dic.Add("isent", isent);
            //ismyblack : 是否在当前用户的黑名单中，0-不是，1-是,
            dic.Add("ismyblack", ismyblack);
            //ismyfans : 是否是当前用户的听众，0-不是，1-是,
            dic.Add("ismyfans", ismyfans);
            //ismyidol : 是否是当前用户的偶像，0-不是，1-是,
            dic.Add("ismyidol", ismyidol);
            //isrealname : 是否实名认证，1-已实名认证，2-未实名认证,
            dic.Add("isrealname", isrealname);
            //isvip : 是否认证用户，0-不是，1-是,
            dic.Add("isvip", isvip);
            //location : 所在地,
            dic.Add("location", location);
            //mutual_fans_num : 互听好友数,
            dic.Add("mutual_fans_num", mutual_fans_num);
            //name : 用户帐户名,
            dic.Add("name", name);
            //nick : 用户昵称,
            dic.Add("nick", nick);
            //openid : 用户唯一id，与name相对应,
            dic.Add("openid", openid);
            //province_code : 地区id,
            dic.Add("province_code", province_code);
            //regtime : 注册时间,
            dic.Add("regtime", regtime);
            //send_private_flag : 是否允许所有人给当前用户发私信，0-仅有偶像，1-名人+听众，2-所有人,
            dic.Add("send_private_flag", send_private_flag);
            //sex : 用户性别，1-男，2-女，0-未填写,
            dic.Add("sex", sex);


            return dic;
        }

        /// <summary>
        /// 返回请求结果返回值；
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private Dictionary<string, string> AnalysisTencentWeiboResult(string json)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            JObject obj = (JObject)JsonConvert.DeserializeObject(json);

            //返回码
            string ret = obj["ret"].ToString().Replace("\"", "");
            //如果ret<0，会有相应的错误信息提示，返回数据全部用UTF-8编码 
            string msg = obj["msg"].ToString().Replace("\"", "");
            dic.Add("ret", ret);
            dic.Add("msg", msg);

            return dic;
        }
    }
}
